<?php

namespace app\common\controller;

use think\Controller;

class YouJanPay extends Controller
{
    /**
     * v3 拉起支付
     * @return $res
     * @return status int 返回码 1=成功 !=1 失败
     * @return message string 响应消息
     * @return pay_url string 支付链接
     * @return qr_code string Base64编码的支付二维码
     * @return data string 微信App支付返回的是预支付交易会话标识prepay_id，云闪付App支付返回的是银联受理订单号tn
     */
    public function toPay($orderInfo,$config,$trade_type)
    {
        $money = $orderInfo['pay_amount'] * 100;
        $str = 'merchant_order_no='.$orderInfo['pay_order_number'].'&money='.$money.'&mch_id='.$config['mchid'].'&key='.$config['key'];
        $sign = md5($str);
        $payUrl = "https://my.youjiankeji.cn/api/v3/pay?notify_url={$orderInfo['notify_url']}&mch_id={$config['mchid']}&money={$money}&terminal_ip={$orderInfo['order_ip']}&return_url={$orderInfo['return_url']}&merchant_order_no={$orderInfo['pay_order_number']}&subject={$orderInfo['props_name']}&subject_desc={$orderInfo['props_name']}&trade_type={$trade_type}&sign={$sign}";
        $res = $this->send_curl($payUrl,[]);
        return $res;
    }
    /**
     * 支付结果查询
     * @return $res
     * @return status int 返回码 1=成功 !=1 失败
     * @return message string 响应消息
     * @return data object 支付结果数据
     */

    public function OrderQuery($conf,$pay_order_number){
        $str = 'merchant_order_no='.$pay_order_number.'&mch_id='.$conf['mchid'].'&key='.$conf['key'];
        $sign = md5($str);
        $url2 = "https://my.youjiankeji.cn/api/v3/pay/query?mch_id={$conf['mchid']}&merchant_order_no={$pay_order_number}&sign={$sign}";
        $res = $this->send_curl($url2,[]);
        return $res;
    }

    public function send_curl($url,$param){
        $ch       = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
        $send_data = curl_exec($ch);
        curl_close($ch);
        //解析返回结果（json格式字符串）
        $backmassage = json_decode($send_data,true);
        return $backmassage;

    }
}
